package com.hcinfos.gsoo.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;

import net.simonvt.numberpicker.NumberPicker;
import net.simonvt.numberpicker.NumberPicker.OnValueChangeListener;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.GdDingzuoConfig;
import com.hcinfos.gsoo.enity.GdMealsDish;
import com.hcinfos.gsoo.enity.GdSupplerBasicConfExt;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.enity.WDoMenuDetailEnity;
import com.hcinfos.gsoo.enity.WDoSumbitEnity;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.util.DateUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

/**
 * 订座提交页面
 * 
 * @author john
 * 
 */
public class DingzuoSubmitActivity extends Activity implements OnClickListener {

	private ToggleButton order_other_tb;
	private LinearLayout other_ll;
	private RelativeLayout num_rl;

	private RelativeLayout choice_num_rl;
	private Button submit_bt;
	private LayoutInflater lif;
	private Dialog dialog;
	private TextView num_tv;
	private RelativeLayout time_rl;

	private TextView name_tv;
	private TextView contact_content_tv;
	private TextView date_tv;
	private TextView tel_tv;
	private ImageView back_iv;
	private GdSupplerBasicConfExt detailExt;
	private ObjectMapper objectMapper;
	private int sex = 0;
	private EditText tel_et;

	public final int DO_ORDER_SUCCESS = 0x2200;
	public final int DO_ORDER_FAIL = DO_ORDER_SUCCESS + 1;
	public final int LOGIN = DO_ORDER_SUCCESS + 2;
	private RadioGroup sex_rb;

	private Dialog progressDialog;
	private EditText orderName_et;
	private SharePreferenceUtil util;
	private User user;
	private GdDingzuoConfig config;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dingzuosubmit);
		util = new SharePreferenceUtil(this, "setting");
		objectMapper = new ObjectMapper();
		lif = getLayoutInflater();
		dialog = createNumDialog();
		progressDialog = DialogUtil
				.createProgressDialog(this, "提示", "正在提交中...");
		initRes();

		detailExt = (GdSupplerBasicConfExt) getIntent().getSerializableExtra(
				"detailExt");
		config = (GdDingzuoConfig) getIntent().getSerializableExtra("config");
		if (detailExt != null) {
			name_tv.setText(detailExt.getSuppName());
			contact_content_tv
					.setText(detailExt.getContactMobile() == null ? "暂无"
							: detailExt.getContactMobile());
		}

		Date d1 = Calendar.getInstance().getTime();
		d1.setHours(d1.getHours() + 1);
		String s1 = new SimpleDateFormat("yyyy" + "-" + "MM" + "-" + "dd HH"
				+ ":" + "mm").format(d1);
		curTime = s1;
		date_tv.setText(s1);
		String[] times = s1.split(" ");
		if (times.length >= 2) {
			selectDate = times[0];
			selectTime = times[1];
		}

	}

	String taStartTime = "07:30";
	String taEndTime = "22:00";

	private void orderTimeCompare(GdDingzuoConfig tabcResult, String time) {
		if (config == null) {
			return;
		}
		int week = DateUtil.dayForWeek(time);
		switch (week) {
		case 1:
			taStartTime = tabcResult.getStartTime1();
			taEndTime = tabcResult.getEndTime1();
			break;
		case 2:
			taStartTime = tabcResult.getStartTime2();
			taEndTime = tabcResult.getEndTime2();
			break;
		case 3:
			taStartTime = tabcResult.getStartTime3();
			taEndTime = tabcResult.getEndTime3();
			break;
		case 4:
			taStartTime = tabcResult.getStartTime4();
			taEndTime = tabcResult.getEndTime4();
			break;
		case 5:
			taStartTime = tabcResult.getStartTime5();
			taEndTime = tabcResult.getEndTime5();
			break;
		case 6:
			taStartTime = tabcResult.getStartTime6();
			taEndTime = tabcResult.getEndTime6();
			break;
		case 7:
			taStartTime = tabcResult.getStartTime7();
			taEndTime = tabcResult.getEndTime7();
			break;
		default:
			break;
		}
		if (taStartTime == null)
			taStartTime = "7:30";
		if (taEndTime == null)
			taEndTime = "10:00";
		LogUtil.d("wxf", "week=" + week + ",start=" + taStartTime + ",end="
				+ taEndTime);
	}

	@Override
	protected void onResume() {
		user = (User) util.loadObject("user");
		if (user != null && user.getTaName() != null) {
			orderName_et.setText(user.getTaName());
			tel_et.setText(user.getTaTelphone());
		} else {

		}
		super.onResume();
	}

	private void initRes() {
		orderName_et = (EditText) findViewById(R.id.orderName_et);
		tel_et = (EditText) findViewById(R.id.tel_et);
		sex_rb = (RadioGroup) findViewById(R.id.sex_rb);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		name_tv = (TextView) findViewById(R.id.name_tv);
		contact_content_tv = (TextView) findViewById(R.id.contact_content_tv);
		date_tv = (TextView) findViewById(R.id.date_tv);

		time_rl = (RelativeLayout) findViewById(R.id.time_rl);
		time_rl.setOnClickListener(this);
		submit_bt = (Button) findViewById(R.id.submit_bt);
		submit_bt.setOnClickListener(this);
		LayoutInflater inflater = getLayoutInflater();
		choice_num_rl = (RelativeLayout) inflater.inflate(
				R.layout.starttime_dialog, null);

		num_tv = (TextView) findViewById(R.id.num_tv);
		num_rl = (RelativeLayout) findViewById(R.id.num_rl);
		num_rl.setOnClickListener(this);
		order_other_tb = (ToggleButton) findViewById(R.id.order_other_tb);
		other_ll = (LinearLayout) findViewById(R.id.other_ll);
		other_ll.setVisibility(View.GONE);
		order_other_tb
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {

						if (isChecked) {
							other_ll.setVisibility(View.VISIBLE);
						} else {
							other_ll.setVisibility(View.GONE);
						}
					}
				});

		sex_rb.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {

				switch (checkedId) {
				case R.id.man_rb:
					sex = 0;
					break;
				case R.id.lady_rb:
					sex = 1;
					break;
				}
			}
		});
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.num_rl:
			dialog.show();
			break;
		case R.id.submit_bt:
			if (user == null) {
				DialogUtil.createCallLoginDialog(DingzuoSubmitActivity.this,
						"请先登陆,再提交!", new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								Intent intent = new Intent(
										DingzuoSubmitActivity.this,
										LoginActivity.class);
								intent.putExtra("type", Constants.LOGIN_CODE);
								startActivityForResult(intent, 1);

							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {
								finish();
							}
						}, "登陆", "取消");

				return;
			}
			if (tel_et.getText().toString().length() == 0
					|| orderName_et.getText().toString().length() == 0) {

				Toast.makeText(DingzuoSubmitActivity.this, "电话信息或者用户名不能为空", 500)
						.show();
				return;
			}

			boolean isCheck = checkTime();

			if (!isCheck) {
				return;
			}
			doSumbitOrder();
			break;
		case R.id.confirm_dialog_cancel_btn:
			dialog.dismiss();
			break;
		case R.id.confirm_dialog_ok_btn:
			num_tv.setText(num + "人");
			dialog.dismiss();
			break;
		case R.id.time_rl:
			intent = new Intent(this, DatePickerActivity.class);
			startActivityForResult(intent, 0);
			break;
		case R.id.back_iv:
			finish();
			break;
		}
	}

	/**
	 * 人数选择dialog
	 */
	private int num = 1;
	private Button confirm_dialog_ok_btn, confirm_dialog_cancel_btn;

	private Dialog createNumDialog() {

		View view = lif.inflate(R.layout.dialog_num_pick_view, null);
		Dialog dialog = new Dialog(this, R.style.QuitDialog);
		dialog.setContentView(view);

		NumberPicker numberPicker = (NumberPicker) view
				.findViewById(R.id.numberPicker);
		confirm_dialog_ok_btn = (Button) view
				.findViewById(R.id.confirm_dialog_ok_btn);
		confirm_dialog_ok_btn.setOnClickListener(this);
		confirm_dialog_cancel_btn = (Button) view
				.findViewById(R.id.confirm_dialog_cancel_btn);
		confirm_dialog_cancel_btn.setOnClickListener(this);

		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (280 * Common.PROPORTION); // 宽度
		lp.height = (int) (220 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);

		numberPicker.setMaxValue(20);
		numberPicker.setMinValue(1);
		numberPicker.setFocusable(false);
		numberPicker.setFocusableInTouchMode(false);
		numberPicker.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				num = newVal;
				LogUtil.d("wxf", "newVal" + newVal + ",num=" + num);
			}
		});
		return dialog;
	}

	/**
	 * 提交订单信息
	 */
	private String orderId;

	private void doSumbitOrder() {

		progressDialog.show();
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);

		RequestParams params = new RequestParams();
		params.addBodyParameter("order", getParams());
		LogUtil.d("wxf", "params=" + getParams());
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_GET_SUBMIT, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(DO_ORDER_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {
						LogUtil.d("wxf", "orderInfo = " + text.result);
						try {
							JSONObject obj = new JSONObject(text.result);
							String message = obj.getString("message");
							int state = obj.getInt("state");
							if (state == 200) {
								orderId = obj.getJSONObject("data").getString(
										"id");
								handler.sendEmptyMessage(DO_ORDER_SUCCESS);
							} else if (state == 198) {
								handler.sendEmptyMessage(LOGIN);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = DO_ORDER_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(DO_ORDER_FAIL);

						}
					}
				});
	}

	private String curTime = "";

	private String getParams() {

		List<WDoMenuDetailEnity> list = new ArrayList<WDoMenuDetailEnity>();
		Map<String, GdMealsDish> orderMap = GsooApplication.menuMap;
		for (String key : orderMap.keySet()) {
			GdMealsDish extend = orderMap.get(key);
			WDoMenuDetailEnity enity = new WDoMenuDetailEnity();
			enity.setDishId(extend.getId());
			enity.setNum(extend.getNum());
			list.add(enity);
		}

		WDoSumbitEnity enity = new WDoSumbitEnity();
		enity.setPayState("1");
		enity.setOrderType("2");
		enity.setPersonSum(num);
		enity.setUserTelphone(tel_et.getText().toString());
		enity.setOrderDetails(list);
		enity.setSuppId(detailExt.getId());
		enity.setSex(sex);
		enity.setContactName(orderName_et.getText().toString());
		enity.setSuppNick(detailExt.getSuppName());
		enity.setOtTime(curTime);
		try {
			String result = objectMapper.writeValueAsString(enity);
			return result;
		} catch (Exception e) {

			return null;
		}

	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case DO_ORDER_FAIL:
				dialog.dismiss();
				String errorMsg = "订单提交失败";
				if (msg.obj != null)
					errorMsg = msg.obj.toString();
				Toast.makeText(DingzuoSubmitActivity.this, errorMsg, 500)
						.show();
				break;
			case DO_ORDER_SUCCESS:
				GsooApplication.menuMap.clear();
				intent = new Intent(DingzuoSubmitActivity.this,
						DingzuoOrderDetailActivity.class);
				intent.putExtra("orderId", orderId);
				startActivity(intent);
				finish();
				break;
			case LOGIN:
				LoginUtil.isLoginSuccess(DingzuoSubmitActivity.this, handler);
				break;
			case LoginUtil.LOGIN_FAIL:
				dialog.dismiss();
				Toast.makeText(DingzuoSubmitActivity.this, "提交失败!", 500).show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				LogUtil.d("wxf", "SUCCESS");
				doSumbitOrder();
				break;
			}
		}
	};

	private String selectDate = "";
	private String selectTime = "";

	private boolean checkTime() {

		orderTimeCompare(config, selectDate);
		LogUtil.d("wxf", "checkTime=" + taStartTime + "," + taEndTime
				+ ",selctTime=" + selectTime);
		if (DateUtil.compare_date(selectTime, taStartTime) < 0
				|| DateUtil.compare_date(selectTime, taEndTime) > 0) {

			Toast.makeText(this, "这个时间段内不接受订座，如有不清楚 请联系商家!", 500).show();
			return false;
		}
		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			curTime = data.getStringExtra("date");
			if (curTime != null) {
				String[] times = curTime.split(",");
				selectDate = times[0];
				selectTime = times[1];
				if (times.length >= 2) {
					date_tv.setText(selectDate + " " + selectTime);
				}

			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	};
}
